package com.hw.core.system.controller;

import com.hw.core.system.entity.Course;
import com.hw.core.system.entity.NoteBook;
import com.hw.core.system.entity.User;
import com.hw.core.system.service.CourseService;
import com.hw.core.system.service.NoteBookService;
import com.hw.core.util.UuidUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("noteBook")
public class NoteBookController {
    private static final Logger logger = LoggerFactory.getLogger( NoteBookController.class );

    @Autowired
    private NoteBookService noteBookService;
    @Autowired
    private CourseService courseService;

    @PostMapping("add")
    @RequiresPermissions(value = "笔记新增")
    @ResponseBody
    public String myAdd(NoteBook noteBook) {
        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipal();
        noteBook.setUser( new User( loginUser.getId() ) );
        noteBook.setImg( "/img/noteBook/default.jpg" );
        noteBook.setStatus( 0 );
        noteBookService.add( noteBook );
        return "添加成功";
    }


    @RequiresPermissions(value = "笔记换图")
    @GetMapping("editImg")
    public String myEditImg(Integer id, Model model) {

        NoteBook noteBookById = noteBookService.findNoteBookById( id );
        model.addAttribute( "noteBook", noteBookById );
        return "noteBook/editNoteBookImg";
    }

    @RequiresPermissions(value = "笔记换图")
    @PostMapping("editImg")
    @ResponseBody
    public String myEditImg(Integer id, MultipartFile myfile) throws IOException {

        if (myfile != null) {
            String fileName = myfile.getOriginalFilename();// 文件原名称
            //带点的类型
            String type = fileName.indexOf( "." ) != -1 ? fileName.substring( fileName.lastIndexOf( "." ), fileName.length() ) : null;
            NoteBook noteBook = noteBookService.findNoteBookById( id );
            String newName = UuidUtil.getUUid();
            File file1 = new File( rootPath + "img/noteBook/" + newName +noteBook.getName() + type );
            String img = noteBook.getImg();
            if (!"/img/noteBook/default.jpg".equals( img )) {
                File file = new File( rootPath + img );
                if (file.isFile()) {
                    file.delete();
                    logger.info( img + "被删除" );
                }
            }
            myfile.transferTo( file1 );
            logger.info( file1.getName() + "被创建" );
            noteBookService.updateImg( id, "/img/noteBook/" + newName +noteBook.getName() + type );
            return "上传成功";
        } else {
            return "上传失败";
        }
    }

    @RequiresPermissions(value = "我的笔记修改")
    @GetMapping("myEditText")
    public String editText(Integer id, Model model) {

        NoteBook noteBookById = noteBookService.findNoteBookById( id );
        model.addAttribute( "noteBook", noteBookById );
        return "noteBook/editNoteBookText";
    }

    @RequiresPermissions(value = "全部笔记修改")
    @GetMapping("allEditText")
    public String allEditText(Integer id, Model model) {
        NoteBook noteBookById = noteBookService.findNoteBookById( id );
        model.addAttribute( "noteBook", noteBookById );
        return "noteBook/editNoteBookText";
    }


    @RequiresPermissions(value = {"我的笔记修改", "全部笔记修改"}, logical = Logical.OR)
    @PostMapping("EditText")
    @ResponseBody
    public String editText(Integer id, String text) {
        noteBookService.updateText( id, text );
        return "修改成功";
    }


    @RequiresPermissions(value = "我的笔记修改")
    @PostMapping("myEditNameAndStatus")
    @ResponseBody
    public String myEdit(Integer id, String name, Integer status) {
        noteBookService.updateNameAndStatus( id, name, status );
        return "修改成功";
    }

    @RequiresPermissions(value = "全部笔记修改")
    @PostMapping("allEditNameAndStatus")
    @ResponseBody
    public String allEdit(Integer id, String name, Integer status) {
        noteBookService.updateNameAndStatus( id, name, status );
        return "修改成功";
    }

    @RequiresPermissions(value = "我的笔记删除")
    @PostMapping("myDelete")
    @ResponseBody
    public String myDelete(Integer id) {
        NoteBook noteBookById = noteBookService.findNoteBookById( id );
        String img = noteBookById.getImg();
        noteBookService.delete( id );
        if (!"/img/noteBook/default.jpg".equals( img )) {
            File file = new File( rootPath + img );
            if (file.isFile()) {
                file.delete();
                logger.info( img + "被删除" );

            }

        }
        return "删除成功";
    }

    @RequiresPermissions(value = "全部笔记删除")
    @PostMapping("allDelete")
    @ResponseBody
    public String allDelete(Integer id) {
        NoteBook noteBookById = noteBookService.findNoteBookById( id );
        String img = noteBookById.getImg();
        noteBookService.delete( id );
        if (!"/img/noteBook/default.jpg".equals( img )) {
            File file = new File( rootPath + img );
            if (file.isFile()) {
                file.delete();
                logger.info( img + "被删除" );

            }

        }
        return "删除成功";
    }

    @RequiresPermissions(value = "笔记转课程")
    @PostMapping("change")
    @ResponseBody
    public String change(Integer id) {
        NoteBook noteBookById = noteBookService.findNoteBookById( id );
        Course course = new Course();
        course.setImg( "/img/course/default.jpg" );
        course.setName( noteBookById.getName() );
        course.setText( noteBookById.getText() );
        course.setAuthor( noteBookById.getUser() );
        courseService.add( course );

        String img = noteBookById.getImg();
        noteBookService.delete( id );
        if (!"/img/noteBook/default.jpg".equals( img )) {
            File file = new File( rootPath + img );
            if (file.isFile()) {
                file.delete();
                logger.info( img + "被删除" );
            }
        }
        return "转换成功";
    }


    @GetMapping("my")
    @RequiresPermissions(value = "我的笔记查询")
    public String myList(Model model, Integer page, String name) throws Exception {
        Subject currentUser = SecurityUtils.getSubject();
        User loginUser = (User) currentUser.getPrincipal();
        Page<NoteBook> noteBookPage = null;
        if (page == null) {
            noteBookPage = noteBookService.findMyNoteBook( loginUser.getId(), 1, 8, name );
        } else {
            if (page < 1)
                throw new Exception( "参数错误" );
            noteBookPage = noteBookService.findMyNoteBook( loginUser.getId(), page, 8, name );
        }
        model.addAttribute( "name", name );
        model.addAttribute( "noteBookPage", noteBookPage );
        return "noteBook/myNoteBook";
    }


    @GetMapping("all")
    @RequiresPermissions(value = "全部笔记查询")
    public String allList(Model model, Integer page, String name) throws Exception {
        Page<NoteBook> noteBookPage = null;
        if (page == null) {
            noteBookPage = noteBookService.findAllNoteBook( 1, 8, name );
        } else {
            if (page < 1)
                throw new Exception( "参数错误" );
            noteBookPage = noteBookService.findAllNoteBook( page, 8, name );
        }
        model.addAttribute( "name", name );
        model.addAttribute( "noteBookPage", noteBookPage );
        return "noteBook/allNoteBook";
    }


    @Value("${img.url.rootPath}")
    private String rootPath;

    @PostMapping("upload")
    @ResponseBody
    @RequiresPermissions(value = "笔记图片上传")
    public Map upload(MultipartFile file) throws IOException {
        Subject currentUser = SecurityUtils.getSubject();
        User principal = (User) currentUser.getPrincipal();
        Map<String, Object> map = new HashMap<>();
        if (file != null) {
            String fileName = file.getOriginalFilename();// 文件原名称
            //带点的类型
            String type = fileName.indexOf( "." ) != -1 ? fileName.substring( fileName.lastIndexOf( "." ), fileName.length() ) : null;
            String newName = UUID.randomUUID().toString();
            File file1 = new File( rootPath + "img/noteBookText/" +principal.getName()+ newName + type );
            file.transferTo( file1 );
            map.put( "errno", 0 );
            map.put( "data", new String[]{"/img/noteBookText/" +principal.getName()+ newName + type} );
        } else {
            map.put( "errno", 1 );
            map.put( "data","上传文件空" );
        }

        return map;
    }
}
